package com.huaxin.common.view;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;

import com.huaxin.common.tools.Log;

/**
 * explained by:guokailin
 * 自定义的视图，实现登录界面背景的左右平移动画
 */
public class SimpleScrollBackgroundView extends View {
    final int fps = 10;
    final int step = 5;//平移步长
    int width;
    TranslateAnimation from;
    boolean scrollable = true;
    int moveMode = Animation.REVERSE;

    public SimpleScrollBackgroundView(Context context) {
        super(context);
        init();
    }

    public SimpleScrollBackgroundView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public SimpleScrollBackgroundView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public SimpleScrollBackgroundView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    protected void init() {
        if (!scrollable) {
            return;
        }
        if (getBackground() == null) {
            throw new RuntimeException("Not found Background.");
        }
        width = getBackground().getIntrinsicWidth();
        if (width == 0) {
            Log.w("get width from Background failed.");
            width = getResources().getDisplayMetrics().widthPixels;
        } else if (width < getResources().getDisplayMetrics().widthPixels * 2 / 3) {
            width = getResources().getDisplayMetrics().widthPixels * 2 / 3;
        }
        from = new TranslateAnimation(0, -width / 2f, 0, 0);
        from.setDuration(((1000 / fps) * width) / (2 * step));
        from.setRepeatCount(-1);//forever
        from.setRepeatMode(moveMode);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (scrollable) {
            setMeasuredDimension(2 * width, getResources().getDisplayMetrics().heightPixels);
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (from != null) {
            startAnimation(from);
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (from != null) {
            from.cancel();
        }
        clearAnimation();
    }
}